<template>
<div>
  <!--面包屑导航-->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item><a href="/users">用户管理</a></el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--卡片视图-->
  <el-card>
    <!--搜索和添加区域-->

    <el-row :gutter="20">
      <el-col :span="9">
        <el-input placeholder="请输入内容" @clear="getUserList" clearable v-model="queryInfo.query" class="input-with-select">
          <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialogVisible =true">添加用户</el-button>
      </el-col>
    </el-row>

    <template>
      <el-table :data="userlist" stripe border style="width: 100%">
        <el-table-column type="index" label=" 编号"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!--作用域插槽拿到数据-->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="suerStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!--修改-->
            <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
            <!--删除-->
            <el-button size="mini" @click="removeUserById(scope.row.id)" type="danger" icon="el-icon-delete"></el-button>
            <!--分配角色-->
            <el-tooltip effect="dark" :enterable="false" content="分配角色" placement="top">
              <el-button size="mini" @click="setRole(scope.row)" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页区域-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 30, 100]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!--添加用户的对话框-->
    <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="输入用户名" v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" placeholder="请输入邮箱" v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="number" placeholder="请输入手机号码" v-model="addForm.mobile"></el-input>
        </el-form-item>

      </el-form>

      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改用户的对话框-->
    <el-dialog title="修改用户" @close="editDiaLogClose" :visible.sync="editDiaLog" width="50%">

      <el-form :model="editFrom" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input placeholder="输入用户名" disabled v-model="editFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" placeholder="请输入邮箱" v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input type="number" placeholder="请输入手机号码" v-model="editFrom.mobile"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDiaLog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>

  <!--分配角色对话框-->
  <el-dialog title="分配角色" @close="setRoleDialogClosed" :visible.sync="setRoleDialogVisible" width="50%">
    <div>
      <p>当前的用户:{{userInfo.username}}</p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>分配新角色:
        <template>
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </template>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRoleDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

</el-card>
</div>
</template>

<script>
export default {
  name: "User",
  data() {
    //自定义邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    //自定义手机号码样子规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      //获取用户列表的对象
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      //控制添加对话框的显示隐藏
      addDialogVisible: false,
      //添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: null

      },
      //添加表单验证规则
      addFormRules: {
        username: [{
            required: true,
            message: '输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [{
          required: true,
          message: '输入密码',
          trigger: 'blur'
        }, {
          min: 6,
          max: 15,
          message: '长度在 6 到 15 个字符',
          trigger: 'blur'
        }],
        email: [{
            required: true,
            message: '输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{
            required: true,
            message: '手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }

        ]
      },
      //控制修改对话框 的显示隐藏
      editDiaLog: false,
      //保存修改数据
      editFrom: {},
      //修改用户验证
      editFormRules: {
        email: [{
            required: true,
            message: '输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{
            required: true,
            message: '手机号',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }

        ]
      },
      //控制分配角色对话框 显示隐藏
      setRoleDialogVisible: false,
      //需要被分配角色的用户信息
      userInfo: {},
      //所有角色的数据列表
      rolesList: [],
      //已选中的角色id值
      selectRoleId: ''

    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$http
        .get("users", {
          params: this.queryInfo,
        })
        .then((res) => {
          if (res.data.meta.status !== 200)
            return this.$message.error("获取数据失败!");
          this.userlist = res.data.data.users;
          this.total = res.data.data.total;
          console.log(res.data);
        });
    },
    handleSizeChange(newSize) {
      //监听pagesize的
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      //监听页码值改变事件
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    suerStateChange(userinfo) {
      //监听switch提出、开关状态的开关
      console.log(userinfo);
      this.$http
        .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        .then((res) => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("更新状态失败");
            userinfo.mg_state = !userinfo.mg_state;
          }
          this.$message.success("更新状态成功");
        });
    },
    addDialogClosed() {
      //监听对话框的关闭事件表单重置
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      //点击按钮添加用户
      this.$refs.addFormRef.validate(vaild => {
        if (!vaild) return
        //可以发起添加用户的请求
        this.$http.post('users', this.addForm).then(res => {
          if (res.data.meta !== 201) {
            this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
          this.addDialogVisible = false
          this.getUserList()
        })
      })
    },
    showEditDialog(id) {
      //展示编辑的对话框修改按钮
      this.editDiaLog = true
      this.$http.get(`users/${id}`).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取数据失败')
        this.editFrom = res.data.data
      })
    },
    editDiaLogClose() {
      //监听修改用户对话框的关闭事件
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      //修改信息用户提交
      this.$refs.editFormRef.validate(vaild => {
        if (!vaild) return
        //发起修改请求
        this.$http.put('users/' + this.editFrom.id, this.editFrom).then(res => {
          // console.log(res.data.meta.status)
          if (res.data.meta.status !== 200) {
            return this.$message.error('修改用户失败')
          }
          this.$message.success('修改用户成功')
          this.editDiaLog = false
          this.getUserList()
        })
      })
    },
    //根据id删除用户
    removeUserById(id) {
      //弹框
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$http.delete('users/' + id).then(re => {
          console.log(re)
          if (re.data.meta.status !== 200) {
            return this.$message.error('删除用户失败')
          }
          this.$message.success('删除用户成功')
          // this.editDiaLog = false
          this.getUserList()
        })
      }).catch(error => {
        this.$message.error('已经取消删除')
      })

    },
    //分配角色事件
    setRole(userinfo) {
      this.userInfo = userinfo

      //在展示对话框之前获取角色列表
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取角色失败')
        }
        this.rolesList = res.data.data
      })
      this.setRoleDialogVisible = true
    },
    //点击按钮分配角色
    saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择角色')
      }
      //发送分配角色请求
      this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      }).then(res => {
        if (res.data.meta.status !== 200) {
          this.$message.error('更新角色失败')
        }
        this.$message.success('更新角色成功')
        this.getUserList()
        this.setRoleDialogVisible = false
      })
    },
    //监听分配角色对话框隐藏
    setRoleDialogClosed() {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  },

};
</script>

<style lang="less" scoped>
</style>
